#include <stdlib.h>
#include <string.h>
#include "lib.h"


#ifdef WIN32
#include "sys_call_pc.h"
#else 
#include "sys_call.h"
#endif


//-------------------------------------------------------------------------
// Memory Manage
//-------------------------------------------------------------------------
#if (MEMORY_ALLOC_DEBUG & 1)
U32 g_nCount = 0;
#endif
U8 *mem_Malloc(U32 nSize)
{
	U8 *p;
	while (1) {
		tsk_lock();
		p = (U8*)malloc(nSize);
		tsk_unlock();
		if (p != NULL)
			break;
		os_dly_wait(1);
	}
#if (MEMORY_ALLOC_DEBUG & 1)
	printf("<<< MEM >>> Malloc Succeed, Size:%d, pBuf:%X\n", nSize, (U32)p);
#endif 
#if (MEMORY_ALLOC_DEBUG & 2)
	g_nCount++;
#endif
	return p;
}

//-------------------------------------------------------------------------
//
//-------------------------------------------------------------------------
U32 mem_Realloc(U8 **p, U32 nNewSize)
{
	U8 *pTemp;
	tsk_lock();
	if (*p == NULL) {
		*p = mem_Malloc(nNewSize);
	}
	else{
		pTemp = (U8*)realloc(*p, nNewSize);
		if (pTemp != NULL) {
			*p = pTemp;
#if (MEMORY_ALLOC_DEBUG & 1)
			printf("<<< MEM >>> Realloc Succeed, NewSize:%d, pNewBuf:%X\n", nNewSize, (U32) *p);
#endif 
		} else {
			pTemp = mem_Malloc(nNewSize);
			memcpy(pTemp, *p, nNewSize);
			mem_Free(p);
			*p = pTemp;
		}
	}
	tsk_unlock();
	return nNewSize;
}

//-------------------------------------------------------------------------
//
//-------------------------------------------------------------------------
void mem_Free(U8 **pp)
{
	if ((*pp == NULL) || (pp == NULL)) { 
		return;
	}
	tsk_lock();
	free(*pp);
#if (MEMORY_ALLOC_DEBUG & 1)
	printf("<<< MEM >>> Free Succeed, pBuf:%X\n", (U32)*pp);
#endif 
	*pp = NULL;
#if (MEMORY_ALLOC_DEBUG & 2)
	g_nCount--;
#endif
	tsk_unlock();
}

